package com.erp.gather.listener;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.gather.domain.ErpAutoCollectProductTemporary;
import com.erp.gather.mapper.*;
import com.rabbitmq.client.Channel;
import com.ruoyi.ae.api.RemoteAeProductService;
import com.ruoyi.auto.api.RemoteAutoPublishProductService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.gather.api.domain.dto.AeAutoProductDto;
import com.ruoyi.gather.api.domain.dto.TaskStatusDto;
import com.ruoyi.shop.api.RemoteSellerStorePriceTemplateService;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStorePriceTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;

import static jodd.util.ThreadUtil.sleep;

/**
 * 监听路由信息
 *
 * @Author: j.zh
 * @Date: 2024/3/12
 * @Version: 1.0
 **/
@Slf4j
@Component
@RabbitListener(queues = "auto.ae.product.set.data.queue", ackMode = "MANUAL")
public class AutoAeProductSetDataListener {

    @Resource
    ErpAutoCollectProductTemporaryMapper erpAutoCollectProductTemporaryMapper;


    @Resource
    ErpCollectProductExpandMapper collectProductExpandMapper;

    @Resource
    RemoteAeProductService remoteAeProductService;
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    RemoteSellerStorePriceTemplateService remoteSellerStorePriceTemplateService;
    @Resource
    RemoteAutoPublishProductService remoteAutoPublishProductService;

    /**
     * 进行速卖通上架后操作
     *
     * @param info
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void listener(String info, Channel channel, Message message) throws IOException {

        try {
            System.out.println("=============接收消息，消息队列开始执行（进行速卖通上架后操作）");
            // 回复队列消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            // 将JSON字符串转换为实体类
            AeAutoProductDto dto = JSONObject.parseObject(info, AeAutoProductDto.class);
            // 执行公共库至个人库操作
            R<Object> resultOne = aeProductSetData(dto);
            if (resultOne.getCode() == 500) {
                System.out.println("=============执行失败");
            }
        } catch (Exception e) {
            // TODO 消费异常，设置入库操作

            System.out.println("=============执行异常：" + e.toString());
        }

    }

    /**
     * 进行速卖通上架后操作
     *
     * @param dto
     */
    @Async("aeProductSetDataMq")
    public R<Object> aeProductSetData(AeAutoProductDto dto) {
        Integer storeType = dto.getStoreType();
        Integer status = 2;
        StringBuffer msg = new StringBuffer();

        if (storeType == 0) {
            //为0则代表子账号或者测试发布
            status = 3;
            msg.append("|可能为子账号，无需设置联盟折扣");
        } else {
            //增加联盟折扣
            R<Object> objectR = setCommission(dto);
            if (objectR.getCode() != 200) {
                status = 3;
                msg.append("|联盟折扣设置异常");
            } else {
                msg.append("|联盟折扣设置成功");
            }
            //4、从临时库中移除该品
            //查找临时表中数据
            ErpAutoCollectProductTemporary temporaryProduct = erpAutoCollectProductTemporaryMapper.selectOne(
                    new LambdaQueryWrapper<ErpAutoCollectProductTemporary>()
                            .eq(ErpAutoCollectProductTemporary::getCollectProductId, dto.getCollectProductId())
            );
            if (ObjectUtils.isNotNull(temporaryProduct)) {
                erpAutoCollectProductTemporaryMapper.deleteById(temporaryProduct);
            }
        }

        //返回消息给task任务
        TaskStatusDto taskStatusDto = new TaskStatusDto();
        taskStatusDto.setStatus(status);
        taskStatusDto.setMsg(msg.toString());
        taskStatusDto.setId(dto.getAutoTaskId());
        remoteAutoPublishProductService.updateTaskStatus(taskStatusDto);
        return R.ok();
    }

    private R<Object> setCommission(AeAutoProductDto autoProductDto) {
        BigDecimal afflicateDiscount = null;
        if (autoProductDto.getIsAfflicateDiscount() == 1) {
            afflicateDiscount = new BigDecimal(autoProductDto.getAfflicateDiscount());
        } else {
            R<Object> templateR = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(autoProductDto.getTemplateId()));
            String templateString = JSONObject.toJSONString(templateR.getData());
            ErpSellerStorePriceTemplate template = JSONObject.parseObject(templateString, ErpSellerStorePriceTemplate.class);
            afflicateDiscount = template.getUnion();
        }
        if (afflicateDiscount.compareTo(BigDecimal.ZERO) > 0) {
            //调用孙哥方法
            R<Object> commissionObjectR = remoteSellerStoreService.setCommission(autoProductDto.getStoreId(), autoProductDto.getAeProductId(), afflicateDiscount.intValue());
            if (commissionObjectR.getCode() != 200) {
                return R.fail(commissionObjectR.getMsg().toString());
            } else {
                return R.ok("联盟折扣设置成功");
            }
        } else {
            return R.ok("无需设置联盟折扣");
        }
    }


}
